package wili.insertCode;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 *
 */
public class InsertStrings {
	public static class Item {
		public String st;

		public int coverNum;

		public String toString() {
			if (coverNum == 0)
				return st;
			return coverNum + ":" + st;
		}

		/**
		 * ..So can insert $st and remove original subString with $coverNum length.
		 */
		public Item(String st, int coverNum) {
			this.st = st;
			this.coverNum = coverNum;
		}
	}

	private TreeMap<Integer, List<Item>> insertMap;

	public void addInsert(int from, String str, int coverNum) {
		if (insertMap == null)
			insertMap = new TreeMap<>();
		List<Item> lis = insertMap.get(from);
		if (lis == null) {
			insertMap.put(from, lis = new ArrayList<>());
		} else {
			if (lis.get(lis.size() - 1).coverNum > 0)
				Coms2.asert(false, "if coverNum >0, must be last insertion.");
		}
		lis.add(new Item(str, coverNum));

	}

	public String insertInto(String s0) {
		if (insertMap == null || insertMap.isEmpty())
			return s0;
		StringBuffer sb = new StringBuffer(s0.length() + insertMap.size() * 10);
		int from = 0;
		for (Integer insertInd : insertMap.keySet()) {
			if (from < insertInd) {
				sb.append(s0.substring(from, insertInd));
				from = insertInd;
			}
			List<Item> items = insertMap.get(insertInd);
			for (Item ele : items) {
				sb.append(ele.st);
				if (ele.coverNum > 0) {
					from += ele.coverNum;
				}
			}
		}
		sb.append(s0.substring(from));
		return sb.toString();
	}
}
